#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h>
#include <time.h> 

int mySocket = -1;
int connection(const char * src)
{
    int sockfd = 0, n = 0;
    char recvBuff[1024];
    struct sockaddr_in serv_addr; 

    memset(recvBuff, '0',sizeof(recvBuff));
    if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        printf("\n Error : Could not create socket \n");
        return 1;
    } 
    mySocket = sockfd       ;
    memset(&serv_addr, '0', sizeof(serv_addr)); 

    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(5000); 

    if(inet_pton(AF_INET, src, &serv_addr.sin_addr)<=0)
    {
        printf("\nClient : inet_pton error occured\n");
        return 1;
    } 
    if( connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
    {
       printf("\nClient error : Connect Failed \n");
       return 1;
    }
    return 0;
}

void send_message(int socket_fd, void* buffer, int sizeofBuffer)
{
    if ((send(socket_fd,buffer, strlen(buffer),0))== -1) {
        fprintf(stderr, "\nClient : Failure Sending Message\n");
        close(socket_fd);
        exit(1);
    }
}

int read_message(int sockfd, void* recvBuff, int sizeofBuffer)
{
    int n=0;
    bzero(recvBuff,sizeofBuffer);

    n = read(sockfd,recvBuff,sizeofBuffer);
    if (n < 0)
    {
        perror("ERROR reading from socket");
        exit(1);
    }
    printf("Here is the message: %s\n",(char*)recvBuff);

    return n;
}

int main(int argc, char *argv[])
{
    if(argc != 2)
    {
        printf("\nUsage: %s <ip of server> \n",argv[0]);
        return 1;
    }
    //Connexion
    connection(argv[1]);
    char chaine_choix[64];
    char chaine_msg[64];
    char recvBuff[64];
    int choix = 0, taille = 0;
    //Menu de test fonctions de test envoie
    while(choix == 0){
        printf("\nSaisir votre message :\n");
        fgets(chaine_msg, 64, stdin);

        /* remove newline */
        taille = strlen(chaine_msg);
        if(taille > 0){
        chaine_msg[strlen(chaine_msg) - 1] = '\0';
        }
        send_message(mySocket, chaine_msg, 64);

        if(chaine_msg == "1"){
            read_message(mySocket,recvBuff, 64);
        }
    }

    return 0;
}
